package resp

import (
	"errors"
	"net/http"
)

type ErrorResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func defaultResp() Response {
	return new(r).
		Status(http.StatusOK).
		ContentType(ContentJSONHeaderValue)
}

func New(data interface{}) Response {
	return defaultResp().Data(data)
}

func Ok() Response {
	return defaultResp()
}

func Created(data interface{}) Response {
	return defaultResp().Status(http.StatusCreated).Data(data)
}

func Error(httpStatus int, err error) Response {
	var wrap = ErrorResponse{
		Code: httpStatus,
		Msg:  err.Error(),
	}
	return defaultResp().Status(httpStatus).Data(wrap)
}

func ErrInternalError(err error) Response {
	return Error(http.StatusInternalServerError, err)
}

func ErrBadRequest(msg string) Response {
	return Error(http.StatusBadRequest, errors.New(msg))
}

func Redirect(w http.ResponseWriter, location string) {
	w.WriteHeader(http.StatusFound)
	w.Header().Set("Location", location)
}

func Model() IModelAndView {
	return new(mv)
}

func ModelAndView(model interface{}, view string) Response {
	return Model().SetModel(model).SetView(view).Response()
}
